package com.github_Dididipapa.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github_Dididipapa.shortlink.admin.common.biz.user.UserContext;
import com.github_Dididipapa.shortlink.admin.common.exception.ClientException;
import com.github_Dididipapa.shortlink.admin.common.result.R;
import com.github_Dididipapa.shortlink.admin.dao.entity.Group;
import com.github_Dididipapa.shortlink.admin.dao.mapper.groupMapper;
import com.github_Dididipapa.shortlink.admin.dto.req.UpdateGroupReqDTO;
import com.github_Dididipapa.shortlink.admin.dto.resp.GroupRespDTO;
import com.github_Dididipapa.shortlink.admin.feign.ProjectFeign;
import com.github_Dididipapa.shortlink.admin.remote.dto.resp.LinkGroupCountRespDTO;
import com.github_Dididipapa.shortlink.admin.service.GroupService;
import com.github_Dididipapa.shortlink.admin.toolkit.RandomCodeGenerator;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description: To be defined
 * @author: dididi_papa
 * @email: mitis1624087624@gmail.com
 * @date: 2025/09/10  11:16
 */
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<groupMapper, Group> implements GroupService {

    @Resource(name = "RBloom-user")
    private final RBloomFilter<String> bloomFilter;
    private final groupMapper groupMapper;
    private final ProjectFeign projectFeign;



    @Transactional
    @Override
    public String createGroup(String name) {
        Group group = Group.builder()
                .name(name)
                .username(UserContext.getUsername())
                .gid(RandomCodeGenerator.generateRandomCode())
                .createTime(new Date())
                .updateTime(new Date())
                .delFlag(0)
                .build();
        this.save(group);
        return name;
    }

    @Override
    public List<GroupRespDTO> getByUsername() {
        LambdaQueryWrapper<Group> lambdaQueryWrapper = Wrappers.lambdaQuery(Group.class)
                .eq(Group::getUsername, UserContext.getUsername())
                .eq(Group::getDelFlag, 0)
                .orderByDesc(Group::getSortOrder, Group::getUpdateTime);
        List<Group> groups = groupMapper.selectList(lambdaQueryWrapper);

        List<String> collect = groups.stream().map(Group::getGid).toList();
        R<List<LinkGroupCountRespDTO>> listGroupShortLinkCount = projectFeign.listGroupShortLinkCount(collect);
        List<GroupRespDTO> linkGroupCountRespDTOS = BeanUtil.copyToList(groups, GroupRespDTO.class);
        linkGroupCountRespDTOS.forEach(each -> {
            Optional<LinkGroupCountRespDTO> first = listGroupShortLinkCount.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();

            first.ifPresent(item -> item.setShortLinkCount(each.getShortLinkCount()));
        });

        return linkGroupCountRespDTOS;
    }

    @Override
    public Boolean updateGroup(UpdateGroupReqDTO group) {
        Group target = this.getOne(
                new QueryWrapper<Group>()
                        .eq("gid", group.getGid())
                        .eq("name", group.getName())
        );
        if(target == null) throw new ClientException("没有对应的分组");
        target.setUpdateTime(new Date());
        return this.updateById(target);
    }




}
